#version 330 core
out vec4 FragColor;

in vec3 Normal;
in vec3 ourColor;
in vec2 TexCoord;
in vec3 FragPos;

#define MAX_POINT_LIGHTS 10 // 定义最大点光源的数量

struct PointLight {
    vec3 position;
    vec3 color;
    float intensity;
    float linear;
    float constant;
    float quadratic;
};


uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform int NR_POINT_LIGHTS;
uniform vec3 viewPos;
uniform vec3 ambientColor;// 环境光

uniform sampler2D texture_diffuse1;
uniform sampler2D texture_diffuse2;
uniform sampler2D texture_diffuse3;
uniform sampler2D texture_specular1;
uniform sampler2D texture_specular2;
uniform sampler2D texture_specular3;
uniform bool useEmissiveMap; // 是否使用发光贴图
uniform sampler2D texture_emissive1;


void main()
{
    vec4 diffuseColor = texture(texture_diffuse1, TexCoord) * vec4(ourColor, 1.0);
    vec4 diffuseColor2 = texture(texture_diffuse2, TexCoord) * vec4(ourColor, 1.0);
    vec4 diffuseColor3 = texture(texture_diffuse3, TexCoord) * vec4(ourColor, 1.0);
    vec4 specularColor1 = texture(texture_specular1, TexCoord);
    vec4 specularColor2 = texture(texture_specular2, TexCoord);
    vec4 specularColor3 = texture(texture_specular3, TexCoord);
    vec4 emissiveColor;

    if (useEmissiveMap) {
        emissiveColor = texture(texture_emissive1, TexCoord);
    } else {
        emissiveColor = vec4(0.0); // 不使用发光贴图时，发光颜色为黑色或透明
    }
    
    vec3 norm = normalize(Normal);
    vec3 viewDir = normalize(viewPos - FragPos);
    
    vec3 result = ambientColor * vec3(texture(texture_diffuse1, TexCoord));
    
    for (int i = 0; i < NR_POINT_LIGHTS; i++) {
        vec3 lightDir = normalize(pointLights[i].position - FragPos);
        float distance = length(pointLights[i].position - FragPos);
        
        // 使用PointLight结构体中的衰减参数
        float attenuation = 1.0 / (pointLights[i].constant + pointLights[i].linear * distance + pointLights[i].quadratic * (distance * distance));
        
        // 漫反射
        float diff = max(dot(norm, lightDir), 0.0);
        vec3 diffuse = diff * pointLights[i].color * pointLights[i].intensity * attenuation;
        
        // 镜面反射
        vec3 reflectDir = reflect(-lightDir, norm);  
        float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32);
        vec3 specular = spec * pointLights[i].color * pointLights[i].intensity * attenuation;
        
        result += (diffuse + specular) * vec3(texture(texture_diffuse1, TexCoord));
    }
    
    // 混合所有纹理颜色
    vec4 mixedDiffuse = (diffuseColor + diffuseColor2 + diffuseColor3) / 3.0;
    vec4 mixedSpecular = (specularColor1 + specularColor2 + specularColor3) / 3.0;
    // 将发光贴图的颜色添加到最终颜色中
    FragColor = vec4(result, 1.0) * mix(mixedDiffuse, mixedSpecular, 0.5) + emissiveColor;
}